<?php

namespace app\common;

use app\model\Config;
use app\model\User;
use app\model\UserCollect;
use app\model\UserScoreLog;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\response\Json;

class UserService
{
	
	/**
	 * 收藏
	 * @param $id
	 * @param $uid
	 * @return bool
	 */
	public static function collect($id, $uid)
	{
		
		$row = UserCollect::where(['user_id' => $uid, 'room_id' => $id])->find();
		if ($row) {
			$row->delete();
			return false;
			
		} else {
			UserCollect::create([
				'user_id' => $uid,
				'room_id' => $id,
			]);
			return true;
		}
	}
	
	/**
	 * 变更积分
	 * @param $score
	 * @param $uid
	 * @param $memo
	 * @return true
	 * @throws Exception
	 */
	public static function changeUserScore($score, $uid, $memo)
	{
		$row = User::lock(true)->find($uid);
		if (!$row) {
			throw new Exception('变更积分失败');
		}
		if ($score < 0 && $row->score < abs($score)) {
			throw new Exception('积分不足');
		}
		$before = $row->score;
		$row->score += $score;
		$data = [
			'user_id' => $uid,
			'score' => $score,
			'before' => $before,
			'after' => $row->score,
			'memo' => $memo
		];
		
		// 启动事务
		Db::startTrans();
		try {
			UserScoreLog::create($data);
			$row->save();
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			throw new Exception('积分变更失败');
		}
		
		return true;
	}
	
	/**
	 * 更改用户余额
	 * @param $money
	 * @param $uid
	 * @param $memo
	 * @return bool
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws Exception
	 * @throws ModelNotFoundException
	 */
	public static function changeUserMoney($money, $uid, $memo): bool
	{
		
		$row = User::find($uid);
		if ($money == 0||!$row) {
			throw new Exception('变更金额失败');
		}
		
		if ($money < 0 && $row->money < abs($money)) {
			throw new Exception('余额不足');
		}
		
		$before = $row->money;
		$row->money += $money;
		$data = [
			'user_id' => $uid,
			'money' => $money,
			'before' => $before,
			'after' => $row->money,
			'memo' => $memo
		];
		
		// 启动事务
		Db::startTrans();
		try {
			UserMoneyLog::create($data);
			$row->save();
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			throw new Exception('余额变更失败');
		}
		return true;
	}
	
	/**
	 * 记录足迹
	 * @param $id
	 * @param $uid
	 * @return bool
	 */
	public static function changeUserFoot($id,$uid){
		$row = UserFoot::where(['user_id'=>$uid,'goods_id'=>$id])->find();
		if ($row){
			$row->updatetime=time();
			$row->save();
			return false;
		}else{
			UserFoot::create([
				'user_id' => $uid,
				'goods_id' => $id,
			]);
			return true;
		}
	}
	
	
	
}